#include <iostream>
#include <cstring>
#include <arpa/inet.h>
#include <unistd.h>
#include "Threadqueue.hpp"

class Client {
public:
    Client(const std::string& server_ip, int server_port, ThreadSafeQueue<std::string>& sendQueue, ThreadSafeQueue<std::string>& receiveQueue)
        : server_ip_(server_ip), server_port_(server_port), client_sockfd_(-1), sendQueue_(sendQueue), receiveQueue_(receiveQueue) {}

    // 连接到服务器
    bool connectToServer() {
        client_sockfd_ = socket(AF_INET, SOCK_STREAM, 0);
        if (client_sockfd_ < 0) {
            std::cerr << "Failed to create socket" << std::endl;
            return false;
        }

        struct sockaddr_in server_addr;
        memset(&server_addr, 0, sizeof(server_addr));
        server_addr.sin_family = AF_INET;
        server_addr.sin_port = htons(server_port_);

        if (inet_pton(AF_INET, server_ip_.c_str(), &server_addr.sin_addr) <= 0) {
            std::cerr << "Invalid address/ Address not supported" << std::endl;
            return false;
        }

        if (connect(client_sockfd_, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
            std::cerr << "Connection failed" << std::endl;
            return false;
        }

        std::cout << "Connected to server " << server_ip_ << ":" << server_port_ << std::endl;
        return true;
    }

    // 启动客户端处理：接收和发送
    void start() {
        std::thread send_thread(&Client::sendData, this);
        std::thread receive_thread(&Client::receiveData, this);

        send_thread.join();
        receive_thread.join();
    }

    // 向服务器发送消息，从队列中取数据并发送
    void sendData() {
        while (true) {
            std::string message = sendQueue_.pop();  // 从队列中取出消息
            send(client_sockfd_, message.c_str(), message.size(), 0);
            std::cout << "Sent to server: " << message << std::endl;
        }
    }

    // 从服务器接收消息并存入队列
    void receiveData() {
        char buffer[1024];
        while (true) {
            memset(buffer, 0, sizeof(buffer));
            int bytes_received = recv(client_sockfd_, buffer, sizeof(buffer), 0);
            if (bytes_received > 0) {
                std::string received_message = std::string(buffer);
                receiveQueue_.push(received_message);  // 将接收到的数据存入队列
                std::cout << "Received from server: " << received_message << std::endl;
            } else if (bytes_received <= 0) {
                std::cerr << "Server disconnected or error" << std::endl;
                break;
            }
        }
    }

    // 关闭连接
    void closeConnection() {
        close(client_sockfd_);
        std::cout << "Connection closed" << std::endl;
    }

private:
    std::string server_ip_;
    int server_port_;
    int client_sockfd_;
    ThreadSafeQueue<std::string>& sendQueue_;    // 发送数据队列
    ThreadSafeQueue<std::string>& receiveQueue_; // 接收数据队列
};
